'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Button } from '@/components/ui/button'
import { 
  IconServer, 
  IconCpu, 
  IconMemory, 
  IconDatabase,
  IconRefresh,
  IconAlertCircle,
  IconCheck,
  IconX
} from '@tabler/icons-react'
import { api, checkServiceConnection } from '@/lib/api'
import { toast } from 'sonner'
import AuthGuard from '@/components/AuthGuard'

interface SystemStats {
  status?: string
  uptime?: number
  ai_service?: {
    model_loaded?: boolean
    device?: string
    model_classes?: number
    inference_count?: number
  }
  task_queue?: {
    total_tasks?: number
    running_tasks?: number
    pending_tasks?: number
    completed_tasks?: number
    failed_tasks?: number
    cache_hits?: number
    cache_size?: number
    average_processing_time?: number
  }
  database?: {
    status?: string
    collections?: number
    total_documents?: number
  }
  system?: {
    cpu_usage?: number
    memory_usage?: number
    disk_usage?: number
    load_average?: number[]
  }
}

export default function SystemStatusPage() {
  const [stats, setStats] = useState<any>(null)
  const [serviceStatus, setServiceStatus] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [lastUpdate, setLastUpdate] = useState<Date>(new Date())

  const fetchSystemStats = async () => {
    try {
      setLoading(true)
      
      // 检查服务连接状态
      const connectionStatus = await checkServiceConnection()
      setServiceStatus(connectionStatus)
      
      // 如果AI服务可用，获取系统统计
      if (connectionStatus.aiService) {
        const stats = await api.system.getStats()
        setStats(stats)
      } else {
        setStats(null)
        connectionStatus.errors.forEach(error => toast.error(error))
      }
      
      setLastUpdate(new Date())
    } catch (error: any) {
      console.error('获取系统状态失败:', error)
      toast.error('获取系统状态失败: ' + (error.response?.data?.detail || error.message))
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchSystemStats()
    
    // 定期刷新 - 每30秒
    const interval = setInterval(fetchSystemStats, 30000)
    return () => clearInterval(interval)
  }, [])

  const formatUptime = (seconds?: number) => {
    if (!seconds) return '-'
    
    const days = Math.floor(seconds / 86400)
    const hours = Math.floor((seconds % 86400) / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    
    if (days > 0) return `${days}天 ${hours}小时 ${minutes}分钟`
    if (hours > 0) return `${hours}小时 ${minutes}分钟`
    return `${minutes}分钟`
  }

  const getStatusColor = (status?: string) => {
    if (!status) return 'bg-gray-100 text-gray-800'
    
    switch (status.toLowerCase()) {
      case 'healthy':
      case 'running':
      case 'connected':
        return 'bg-green-100 text-green-800'
      case 'warning':
        return 'bg-yellow-100 text-yellow-800'
      case 'error':
      case 'disconnected':
        return 'bg-red-100 text-red-800'
      default:
        return 'bg-gray-100 text-gray-800'
    }
  }

  const getStatusIcon = (status?: string) => {
    if (!status) return <IconLoader size={16} className="text-gray-600" />
    
    switch (status.toLowerCase()) {
      case 'healthy':
      case 'running':
      case 'connected':
        return <IconCheck size={16} className="text-green-600" />
      case 'warning':
        return <IconLoader size={16} className="text-yellow-600" />
      case 'error':
      case 'disconnected':
        return <IconX size={16} className="text-red-600" />
      default:
        return <IconLoader size={16} className="text-gray-600" />
    }
  }

  const ServiceStatusCard = () => (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center space-x-2">
          <IconServer size={20} />
          <span>服务状态</span>
        </CardTitle>
        <CardDescription>后端服务连接状态</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="flex items-center justify-between">
          <span>AI处理服务 (Python)</span>
          <div className="flex items-center space-x-2">
            {serviceStatus?.aiService ? (
              <>
                <IconCheck size={16} className="text-green-500" />
                <Badge variant="default" className="bg-green-100 text-green-800">在线</Badge>
              </>
            ) : (
              <>
                <IconX size={16} className="text-red-500" />
                <Badge variant="destructive">离线</Badge>
              </>
            )}
          </div>
        </div>
        
        <div className="flex items-center justify-between">
          <span>主服务 (Node.js)</span>
          <div className="flex items-center space-x-2">
            {serviceStatus?.mainService ? (
              <>
                <IconCheck size={16} className="text-green-500" />
                <Badge variant="default" className="bg-green-100 text-green-800">在线</Badge>
              </>
            ) : (
              <>
                <IconX size={16} className="text-red-500" />
                <Badge variant="destructive">离线</Badge>
              </>
            )}
          </div>
        </div>
        
        {serviceStatus?.errors && serviceStatus.errors.length > 0 && (
          <div className="mt-4 p-3 bg-red-50 rounded-lg">
            <div className="flex items-center space-x-2 text-red-700 mb-2">
              <IconAlertCircle size={16} />
              <span className="font-medium">连接错误</span>
            </div>
            {serviceStatus.errors.map((error: string, index: number) => (
              <p key={index} className="text-sm text-red-600">{error}</p>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  )

  if (loading && !stats) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <IconLoader size={48} className="animate-spin mx-auto text-blue-600 mb-4" />
          <p className="text-gray-600">加载系统状态中...</p>
        </div>
      </div>
    )
  }

  return (
    <AuthGuard>
      <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-7xl mx-auto space-y-6">
        {/* 面包屑 */}
        <div className="flex items-center space-x-2 text-sm text-gray-500">
          <span>医疗数字孪生</span>
          <IconChevronRight size={16} />
          <span className="text-blue-600">系统状态</span>
        </div>

        {/* 页面标题 */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">系统状态监控</h1>
            <p className="text-gray-600 mt-1">
              实时监控AI服务运行状态 · 最后更新: {lastUpdate.toLocaleString('zh-CN')}
            </p>
          </div>
          <Button onClick={fetchSystemStats} disabled={loading}>
            <IconRefresh size={16} className={loading ? 'animate-spin' : ''} />
            刷新状态
          </Button>
        </div>

        {/* 系统总览 */}
        <ServiceStatusCard />
        
        {stats && (
          <>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              {/* 服务状态 */}
              <Card>
                <CardContent className="p-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-gray-600">服务状态</p>
                      <div className="flex items-center space-x-2 mt-1">
                        {getStatusIcon(stats.status)}
                        <Badge className={getStatusColor(stats.status)}>
                          {stats.status || '未知'}
                        </Badge>
                      </div>
                    </div>
                    <IconServer size={24} className="text-blue-600" />
                  </div>
                </CardContent>
              </Card>

              {/* 运行时间 */}
              <Card>
                <CardContent className="p-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-gray-600">运行时间</p>
                      <p className="text-lg font-bold text-gray-900">
                        {formatUptime(stats.uptime)}
                      </p>
                    </div>
                    <IconCpu size={24} className="text-green-600" />
                  </div>
                </CardContent>
              </Card>

              {/* AI模型状态 */}
              <Card>
                <CardContent className="p-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-gray-600">AI模型</p>
                      <div className="flex items-center space-x-2 mt-1">
                        {stats.ai_service?.model_loaded ? 
                          <IconCheck size={16} className="text-green-600" /> : 
                          <IconX size={16} className="text-red-600" />
                        }
                        <span className="text-sm font-medium">
                          {stats.ai_service?.model_loaded ? '已加载' : '未加载'}
                        </span>
                      </div>
                    </div>
                    <IconBrain size={24} className="text-purple-600" />
                  </div>
                </CardContent>
              </Card>

              {/* 数据库状态 */}
              <Card>
                <CardContent className="p-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-gray-600">数据库</p>
                      <div className="flex items-center space-x-2 mt-1">
                        {getStatusIcon(stats.database?.status)}
                        <Badge className={getStatusColor(stats.database?.status)}>
                          {stats.database?.status || '未知'}
                        </Badge>
                      </div>
                    </div>
                    <IconDatabase size={24} className="text-orange-600" />
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 详细状态 */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* AI服务详情 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <IconBrain size={20} />
                    <span>AI服务详情</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">运行设备</span>
                    <Badge variant="outline">{stats.ai_service?.device?.toUpperCase() || 'N/A'}</Badge>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">模型类别数</span>
                    <span className="font-medium">{stats.ai_service?.model_classes || 0}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">推理次数</span>
                    <span className="font-medium">{(stats.ai_service?.inference_count || 0).toLocaleString()}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">模型状态</span>
                    <div className="flex items-center space-x-1">
                      {stats.ai_service?.model_loaded ? 
                        <IconCheck size={16} className="text-green-600" /> : 
                        <IconX size={16} className="text-red-600" />
                      }
                      <span className="text-sm">
                        {stats.ai_service?.model_loaded ? '正常运行' : '模型未加载'}
                      </span>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 任务队列状态 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <IconWifi size={20} />
                    <span>任务队列状态</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="text-center p-3 bg-blue-50 rounded-lg">
                      <p className="text-2xl font-bold text-blue-600">
                        {stats.task_queue?.running_tasks || 0}
                      </p>
                      <p className="text-xs text-blue-600">运行中</p>
                    </div>
                    <div className="text-center p-3 bg-yellow-50 rounded-lg">
                      <p className="text-2xl font-bold text-yellow-600">
                        {stats.task_queue?.pending_tasks || 0}
                      </p>
                      <p className="text-xs text-yellow-600">等待中</p>
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">总任务数</span>
                      <span className="font-medium">{stats.task_queue?.total_tasks || 0}</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">已完成</span>
                      <span className="font-medium text-green-600">{stats.task_queue?.completed_tasks || 0}</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">失败</span>
                      <span className="font-medium text-red-600">{stats.task_queue?.failed_tasks || 0}</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">缓存命中</span>
                      <span className="font-medium">{stats.task_queue?.cache_hits || 0}</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">平均处理时间</span>
                      <span className="font-medium">
                        {(stats.task_queue?.average_processing_time || 0).toFixed(2)}s
                      </span>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 数据库详情 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    <IconDatabase size={20} />
                    <span>数据库详情</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">连接状态</span>
                    <div className="flex items-center space-x-1">
                      {getStatusIcon(stats.database?.status)}
                      <span className="text-sm">{stats.database?.status || '未知'}</span>
                    </div>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">集合数量</span>
                    <span className="font-medium">{stats.database?.collections || 0}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-600">文档总数</span>
                    <span className="font-medium">{(stats.database?.total_documents || 0).toLocaleString()}</span>
                  </div>
                </CardContent>
              </Card>

              {/* 系统资源 (如果有的话) */}
              {stats.system && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      <IconMemory size={20} />
                      <span>系统资源</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {stats.system.cpu_usage !== undefined && (
                      <div>
                        <div className="flex justify-between text-sm mb-1">
                          <span className="text-gray-600">CPU使用率</span>
                          <span className="font-medium">{stats.system.cpu_usage.toFixed(1)}%</span>
                        </div>
                        <Progress value={stats.system.cpu_usage} className="h-2" />
                      </div>
                    )}
                    
                    {stats.system.memory_usage !== undefined && (
                      <div>
                        <div className="flex justify-between text-sm mb-1">
                          <span className="text-gray-600">内存使用率</span>
                          <span className="font-medium">{stats.system.memory_usage.toFixed(1)}%</span>
                        </div>
                        <Progress value={stats.system.memory_usage} className="h-2" />
                      </div>
                    )}
                    
                    {stats.system.disk_usage !== undefined && (
                      <div>
                        <div className="flex justify-between text-sm mb-1">
                          <span className="text-gray-600">磁盘使用率</span>
                          <span className="font-medium">{stats.system.disk_usage.toFixed(1)}%</span>
                        </div>
                        <Progress value={stats.system.disk_usage} className="h-2" />
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}
            </div>
                  </>
        )}
      </div>
    </div>
    </AuthGuard>
  )
} 